package cn.wolfcode.luowowo.service.impl;


import cn.wolfcode.luowowo.cache.service.ITravelStatsCacheService;
import cn.wolfcode.luowowo.cache.vo.TravelStats;
import cn.wolfcode.luowowo.common.util.DateUtil;

import cn.wolfcode.luowowo.cache.key.RedisKey;

import com.alibaba.fastjson.JSON;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Service
public class TravelStatsCacheServiceImpl implements ITravelStatsCacheService {

    @Autowired
    private StringRedisTemplate template;

    @Override
    public void setVisitTime(String cacheKey,String createdate) {
        template.opsForValue().set(cacheKey, createdate);
    }


    public void setTravelStats(TravelStats vo) {
        String cacheKey = RedisKey.TRAVEL_STATS.getCacheKey(vo.getTravelId());
        template.opsForValue().set(cacheKey, JSON.toJSONString(vo));
    }
    @Override
    public boolean hasStatsKey(Long TravelId) {
        String cacheKey = RedisKey.TRAVEL_STATS.getCacheKey(TravelId);
        return template.hasKey(cacheKey);
    }

    @Override
    public TravelStats getTravelStats(Long TravelId) {
        String cacheKey = RedisKey.TRAVEL_STATS.getCacheKey(TravelId);
        String json = template.opsForValue().get(cacheKey);
        return JSON.parseObject(json,TravelStats.class);
    }

    public String getTravelVisitTime(String TravelId,String userId) {
        String  key = TravelId.toString() + ":" + userId.toString();
        String cacheKey = RedisKey.TRAVEL_STATS.getCacheKey(key);
        String json = template.opsForValue().get(cacheKey);
        return json;
    }


    @Override
    public boolean favor(Long TravelId, Long userId) {
        boolean flag = true;
        ValueOperations<String, String> op = template.opsForValue();
        //获取文章的所有收藏者在redis中的key
        String cacheKey = RedisKey.TRAVEL_STATS_FAVOR.getCacheKey(TravelId);
        //获取用户收藏的游记key
        String userKey = RedisKey.USER_TRAVEL.getCacheKey(userId);
        //travels,所有游记的id
        List<Long> travels = new ArrayList<>();
        //user,所有收藏者的id
        List<Long> users = new ArrayList<>();
        //num:偏移值
        int num = 0;
        //判断是否有被收藏过

        if (template.hasKey(userKey)){
            String json = op.get(userKey);
            travels = JSON.parseArray(json,Long.class);
        }

        if (template.hasKey(cacheKey)){//有被收藏
            //查询redis中的收藏者
            String vo = op.get(cacheKey);
            //将字符串数据解析成Long类型的数据
            users = JSON.parseArray(vo,Long.class);
            //判断users中是否已有当前登录用户
            if (users.contains(userId)){
                //取消收藏
                users.remove(userId);
                travels.remove(TravelId);
                num = -1;
                flag = false;
            }else {
                //收藏
                users.add(userId);
                travels.add(TravelId);
                num = 1;
            }
        }else{//文章第一次被收藏
            //将当前登录用户id加入list集合
            users.add(userId);
            travels.add(TravelId);
            num = 1;
        }
        //将users存进redis
        op.set(cacheKey,JSON.toJSONString(users));
        //将travels存进redis
        op.set(userKey,JSON.toJSONString(travels));
        //更新收藏数据
        incrNum(TravelId,num,Travel_STATS_FAVORNUM);
        return flag;
    }

    @Override
    public boolean isFavor(Long TravelId, Long userId) {
        String cacheKey = RedisKey.TRAVEL_STATS_FAVOR.getCacheKey(TravelId);
        String vo = template.opsForValue().get(cacheKey);
        if (vo != null){
            List<Long> users = JSON.parseArray(vo,Long.class);
            return users.contains(userId);
        }
       return false;
    }

    @Override
    public boolean TravelThumbup(Long TravelId, Long userId) {
        boolean flag = false;
        //判断当前攻略在缓存在是否有key
        String  key = TravelId.toString() + ":" + userId.toString();
        String cacheKey = RedisKey.TRAVEL_STATS_THUMBUP.getCacheKey(key);
        if(!template.hasKey(cacheKey)){//没有顶过
            Date now = new Date();
            Date endDate = DateUtil.getEndDate(now);
            //往redis中存入key
            template.opsForValue().set(cacheKey,"", DateUtil.getDateBetween(now,endDate), TimeUnit.MILLISECONDS);
            //文章收藏数加1
            incrNum(TravelId,1,ITravelStatsCacheService.Travel_STATS_THUMBSUPNUM);
            flag = true;
        }
        return flag;
    }

  /*  @Override
    public List<TravelStats> listAllStrateg() {
        ValueOperations<String, String> op = template.opsForValue();
        List<TravelStats> vos = new ArrayList<>();
        //根据前缀获取key的集合
        String cacheKey = RedisKey.TRAVEL_STATS.getCacheKey("*");
    }*/


        /*@Override
        public void setTravelStrategyStats (TravelStrategyStats vo){
            String cacheKey = RedisKey.TRAVEL_STATS.getCacheKey(vo.getStrategyId());
            template.opsForValue().set(cacheKey, JSON.toJSONString(vo));
        */

      /*  @Override
        public TravelStrategyStats getTravelStrategyStats (Long strategyId){
            String cacheKey = RedisKey.TRAVEL_STATS.getCacheKey(strategyId);
            String vo = template.opsForValue().get(cacheKey);
            return JSON.parseObject(vo, TravelStrategyStats.class);
        }*/

       /* @Override
        public boolean hasStatsKey(Long strategyId){
            String cacheKey = RedisKey.TRAVEL_STATS.getCacheKey(strategyId);
            return template.hasKey(cacheKey);
        }*/

        @Override
        public List<TravelStats> listAllTravel () {
            ValueOperations<String, String> op = template.opsForValue();
            List<TravelStats> vos = new ArrayList<>();
            //根据前缀获取key的集合
            String cacheKey = RedisKey.TRAVEL_STATS.getCacheKey("*");
            Set<String> keys = template.keys(cacheKey);
            //遍历,将文章数据存进vos
            for (String key : keys) {
                //获取文章数据
                String vo = op.get(key);
                vos.add(JSON.parseObject(vo, TravelStats.class));
            }
            return vos;
        }



        public void addScore (RedisKey key,int num, Long detailId){
            String value = RedisKey.TRAVEL_STATS.getCacheKey(detailId);
            template.opsForZSet().incrementScore(key.getPrefix(), value, num);
        }


        public boolean exist (RedisKey key, Long detailId){
            String value = RedisKey.TRAVEL_STATS.getCacheKey(detailId);
            Long rank = template.opsForZSet().rank(key.getPrefix(), value);
            return rank == null;
        }


        public List<TravelStats> listCommends (RedisKey key){
            List<TravelStats> list = new ArrayList<>();
            ValueOperations<String, String> op = template.opsForValue();
            Set<String> set = template.opsForZSet().reverseRange(key.getPrefix(), 0, 9);
            for (String s : set) {
                String vo = op.get(s);
                list.add(JSON.parseObject(vo, TravelStats.class));
            }
            return list;
        }

        public TravelStats TravelTotal (Long travelId){
            return null;
        }


        @Override
        public Integer anyNum (Long userId) throws Exception {
            String  ikey = "*" + ":" + userId.toString();
            String cacheKey = RedisKey.TRAVEL_STATS.getCacheKey(ikey);
            Set<String> keys = template.keys(cacheKey);
            int num = 0;
            for (String key : keys) {
                String s = template.opsForValue().get(key);
                //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                // Date date = format.parse(s);
                Date dateDay = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String anyDay = sdf.format(dateDay);
                if (s.equals(anyDay)) {
                    num++;
                }
            }
            return num;
        }

        @Override
        public void incrNum (Long strategyId,int num, int type){
            //查询游记内容
            TravelStats vo = getTravelStats(strategyId);
            //偏移值
            switch (type) {
                case TRAVEL_STATS_SHARENUM:
                    vo.setSharenum(vo.getSharenum() + num);
                    break;
                case Travel_STATS_VIEWNUM :
                    vo.setViewnum(vo.getViewnum() + num);
                    break;
            }
            //保存进redis
            setTravelStats(vo);
        }

    @Override
    public List<Long> listTravelsByUserId(Long userId) {
        String cacheKey = RedisKey.USER_TRAVEL.getCacheKey(userId);
        String json = template.opsForValue().get(cacheKey);
        return  JSON.parseArray(json,Long.class);
    }
}
